package com.example.tnot.Teacher.CoursePart.CourseInternal.CourseDetailHome.StudentList;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentResultListener;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.example.tnot.R;
import com.example.tnot.Teacher.CoursePart.CourseInternal.CourseDetailHome.StudentList.Adapter.rv_StudentListAdapter;
import com.example.tnot.Teacher.CoursePart.CourseInternal.CourseDetailHome.StudentList.ItemBean.rv_StudntListItem;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class StudentListFragment extends Fragment {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private rv_StudentListAdapter studentAdapter; // 适配器引用

    private String mParam1;
    private String mParam2;

    private List<rv_StudntListItem> StudentList;
    View view;
    ImageView back;
    RecyclerView rv_StudentList;
    TextView tv_add_student;
    LinearLayout ll_SelectSex,ll_SelectClass;
    private PopupWindow popupWindow;
    private EditText et_search;
    private String selectedClass = "所有班级";
    private String selectedSex = "所有性别";
    private TextView tv_non_student,tv_NumberOfStudent;

    public StudentListFragment() {

    }
    public static StudentListFragment newInstance(String param1, String param2) {
        StudentListFragment fragment = new StudentListFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        StudentList = new ArrayList<>();
        studentAdapter= new rv_StudentListAdapter(StudentList);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.course_student_list_fragment, container, false);
        //每次生成视图时都会初始化数据
        try {
            InitData();
            //如果RecyclerView为空，则显示提示信息
            tv_non_student = view.findViewById(R.id.tv_non_student);
            if(!StudentList.isEmpty()){
                tv_non_student.setVisibility(View.GONE);
            }
            //显示学生数量
            tv_NumberOfStudent = view.findViewById(R.id.tv_NumberOfStudent);
            tv_NumberOfStudent.setText("显示1到10条，共"+StudentList.size()+"条记录");
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
        //设置搜索框监听
        et_search = view.findViewById(R.id.et_search);
        et_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                filterStudentList();
            }
        });
        ll_SelectClass = view.findViewById(R.id.ll_SelectClass);
        // 添加点击监听器
        ll_SelectClass.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showClassDropdown(v);
            }
        });
        ll_SelectSex = view.findViewById(R.id.ll_SelectSex);
        ll_SelectSex.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showSexDropdown(v);
            }
        });
        //学生列别
        rv_StudentList = view.findViewById(R.id.rv_StudentList);
        studentAdapter = new rv_StudentListAdapter(StudentList);
        rv_StudentList.setAdapter(studentAdapter);
        rv_StudentList.setLayoutManager(new LinearLayoutManager(getActivity()));

        //添加学生按钮点击监听
        tv_add_student = view.findViewById(R.id.tv_add_student);
        tv_add_student.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NavController navController = Navigation.findNavController(v);
                navController.navigate(R.id.action_studentListFragment_to_studentListAddStudentFragment);

            }
        });
        // 监听来自添加学生页面 （StudentListAddStudentFragment） 的结果,
        getParentFragmentManager().setFragmentResultListener("add_student_request", this, new FragmentResultListener() {
            @Override
            public void onFragmentResult(@NonNull String requestKey, @NonNull Bundle result) {
                // 获取传递回来的学生信息
                String studentId = result.getString("student_id");
                String name = result.getString("name");
                String sex = result.getString("sex");
                String className = result.getString("class");
                String score = result.getString("score");

                // 创建新的学生对象并添加到列表中
                rv_StudntListItem newItem = new rv_StudntListItem();
                newItem.setID(studentId);
                newItem.setName(name);
                newItem.setSex(sex);
                newItem.setClassname(className);
                newItem.setScore(score);
                newItem.setStatus("正常"); // 设置默认状态

                // 添加到数据列表并更新适配器
                StudentList.add(newItem);
                studentAdapter.updateList(StudentList);
            }
        });

        // 设置删除监听器
        studentAdapter.setOnDeleteClickListener(new rv_StudentListAdapter.OnDeleteClickListener() {
            @Override
            public void onDeleteClick(int position) {
                // 创建确认对话框
                new androidx.appcompat.app.AlertDialog.Builder(requireContext())
                        .setTitle("确认删除")
                        .setMessage("确定要删除学生 " + StudentList.get(position).getName() + " 吗？")
                        .setPositiveButton("确定", (dialog, which) -> {
                            // 从数据列表中移除该项
                            StudentList.remove(position);
                            // 通知适配器数据已更改
                            studentAdapter.notifyItemRemoved(position);
                            // 更新学生数量显示
                            tv_NumberOfStudent.setText("显示1到10条，共"+StudentList.size()+"条记录");
                            // 如果列表为空，显示提示信息
                            if(StudentList.isEmpty()){
                                tv_non_student.setVisibility(View.VISIBLE);
                            }
                        })
                        .setNegativeButton("取消", (dialog, which) -> {
                            // 取消删除操作
                            dialog.dismiss();
                        })
                        .show();
            }
        });

        back = view.findViewById(R.id.back);
        //返回点击监听按钮
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NavController navController = Navigation.findNavController(v);
                navController.navigateUp();
            }
        });
        return view;
    }



    //性别选择下拉菜单
    private void showSexDropdown(View anchorView) {
        // 创建下拉菜单选项
        String[] sexes = {"所有性别", "男", "女"};

        // 创建 PopupWindow 中的内容
        View popupView = LayoutInflater.from(getContext()).inflate(R.layout.popup_class_list, null);
        ListView listView = popupView.findViewById(R.id.lv_class_list);

        ArrayAdapter<String> adapter = new ArrayAdapter<>(getContext(),
                android.R.layout.simple_list_item_1, sexes);
        listView.setAdapter(adapter);

        // 创建 PopupWindow
        PopupWindow popupWindow = new PopupWindow(popupView,
                ll_SelectClass.getWidth(), ViewGroup.LayoutParams.WRAP_CONTENT, true);

        // 设置背景和动画
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
        popupWindow.setAnimationStyle(android.R.style.Animation_Dialog);

        // 在锚点视图下方显示
        popupWindow.showAsDropDown(anchorView);

        // 处理列表项点击事件
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // 获取 LinearLayout 中的 TextView 并更新文本
                TextView textView = (TextView) ((ViewGroup) anchorView).getChildAt(0);
                textView.setText(sexes[position]);
                // 保存选择的性别
                selectedSex = sexes[position];
                // 关闭弹窗
                popupWindow.dismiss();
                // 执行筛选
                filterStudentList();
            }
        });
    }
    //班级选择下拉菜单
    private void showClassDropdown(View anchorView) {
        // 创建下拉菜单选项
        String[] classes = {"所有班级", "一年级(1)班", "一年级(2)班", "二年级(1)班", "二年级(2)班"};

        // 创建 PopupWindow 中的内容
        View popupView = LayoutInflater.from(getContext()).inflate(R.layout.popup_class_list, null);
        ListView listView = popupView.findViewById(R.id.lv_class_list);

        ArrayAdapter<String> adapter = new ArrayAdapter<>(getContext(),
                android.R.layout.simple_list_item_1, classes);
        listView.setAdapter(adapter);

        // 创建 PopupWindow
        PopupWindow popupWindow = new PopupWindow(popupView,
                anchorView.getWidth(), ViewGroup.LayoutParams.WRAP_CONTENT, true);

        // 设置背景和动画
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
        popupWindow.setAnimationStyle(android.R.style.Animation_Dialog);

        // 在锚点视图下方显示
        popupWindow.showAsDropDown(anchorView);

        // 处理列表项点击事件
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // 更新 TextView 文本
                TextView textView = anchorView.findViewById(android.R.id.text1);
                if (textView == null) {
                    textView = (TextView) ((ViewGroup) anchorView).getChildAt(0);
                }
                textView.setText(classes[position]);

                // 保存选择的班级
                selectedClass = classes[position];

                // 关闭弹窗
                popupWindow.dismiss();

                // 执行筛选
                filterStudentList();
            }
        });
    }
    @SuppressLint("SetTextI18n")
    private void filterStudentList() {

        String searchKeyword = et_search.getText().toString().trim().toLowerCase();

        // 创建新的筛选列表
        List<rv_StudntListItem> filteredList = new ArrayList<>();

        for (rv_StudntListItem student : StudentList) {
            boolean matchesSearch = searchKeyword.isEmpty() ||
                    student.getName().toLowerCase().contains(searchKeyword) ||
                    student.getID().toLowerCase().contains(searchKeyword) ||
                    student.getScore().toLowerCase().contains(searchKeyword);

            boolean matchesClass = "所有班级".equals(selectedClass) ||
                    student.getClassname().contains(selectedClass);

            boolean matchesSex = "所有性别".equals(selectedSex) ||
                    student.getSex().equals(selectedSex);

            if (matchesSearch && matchesClass && matchesSex) {
                filteredList.add(student);
            }
        }

        // 更新 RecyclerView
        rv_StudentListAdapter adapter = (rv_StudentListAdapter) rv_StudentList.getAdapter();
        if (adapter != null) {
            adapter.updateList(filteredList);
            tv_NumberOfStudent.setText("显示1到10条，共"+filteredList.size()+"条记录");
            if(filteredList.isEmpty()){
                tv_non_student.setVisibility(View.VISIBLE);
            }
        }
    }


    private void InitData() throws JSONException {
        StudentList = new ArrayList<>();
        if(getArguments() == null)
        {
            Log.e("学生信息","学生信息获取失败！！");
            return ;
        }

        String student_list_json=  getArguments().getString("student_list_json");
        if (student_list_json == null) {
            Log.e("数据传递", "未获取到 JSON 数据");
            return;
        }

        JSONArray student_list = new JSONArray(student_list_json);

        Log.d("学生信息","获取的学生列表:"+student_list);
        for(int i=0;i<student_list.length();i++)
        {
            JSONObject student_data = (JSONObject) student_list.get(i);
            //Log.d("数据获取","获取的学生信息："+student_data);
            String status ="已通过";
            String sex="男";
            if(student_data.getInt("grade") <60 )
            {
                status="未通过";
            }

            if(student_data.getInt("sex") == 0)
            {
                sex="女";
            }
            Log.d("学生信息","性别："+sex);

            StudentList.add(new rv_StudntListItem(
                    status,
                    student_data.getString("id"),
                    R.drawable.ic_launcher_background,
                    student_data.getString("username"),
                    student_data.getString("classname"),
                    String.valueOf(student_data.getInt("grade")),
                    sex,
                    getArguments().getString("CourseTeacher"),
                    student_data.getString("telephone")
            ));
            fresh();
        }
//        StudentList.add(new rv_StudntListItem("已通过", "2021000001", R.drawable.ic_launcher_background, "张三", "软件工程", "90", "男"));
//        StudentList.add(new rv_StudntListItem("未通过", "2021000002", R.drawable.ic_launcher_background, "李四", "软件工程", "80", "女"));
//        StudentList.add(new rv_StudntListItem("未通过", "2021000003", R.drawable.ic_launcher_background, "王五", "软件工程", "70", "男"));
//        StudentList.add(new rv_StudntListItem("未通过", "2021000004", R.drawable.ic_launcher_background, "赵六", "软件工程", "60", "女"));


    }
    private void fresh() {
        if (getActivity() == null) return;

        getActivity().runOnUiThread(() -> {
            if (studentAdapter != null) {
                studentAdapter.notifyDataSetChanged();
            }
        });
    }
}